package com.dreamfire.core
{
	import com.dreamfire.Config;
	import com.dreamfire.asset.AssetManager;
	import com.dreamfire.data.DataManager;
	import com.dreamfire.display.display2D.Viewport2D;
	import com.dreamfire.display.display3D.Viewport3D;
	import com.dreamfire.io.IOManager;
	
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class Client extends Sprite
	{
		//舞台
		public var gameStage:Stage = null;
		//事件派发中心
		public var eventDispatcher:EventDispatcher = null;
		//引擎配置文件
		public var config:Config = null;
		//资源管理器
		public var assetManager:AssetManager = null;
		public var dataManager:DataManager = null;
		public var ioManager:IOManager = null;
		//显示主体
		public var main2D:Viewport2D = null;
		public var main3D:Viewport3D = null;
		
		private static var _instance:Client;
		
		public function Client(stage:Stage, config:Config)
		{
			this.gameStage = stage;
			this.config = config;
			eventDispatcher = new EventDispatcher();
			
			Client._instance = this;
			
			init();
		}
		
		protected function init():void
		{
			assetManager = AssetManager.instance;
			dataManager = DataManager.instance;
			ioManager = IOManager.instance;
			
			switch(config.mode)
			{
				case Config.MODE_2D:
					main2D = new Viewport2D(gameStage.stageWidth, gameStage.stageHeight);
					this.addChild(main2D);
					break;
				case Config.MODE_3D:
					main3D = new Viewport3D(gameStage);
					this.addChild(main3D);
					break;
			}
		}
		
		public static function get instance():Client
		{
			return _instance;
		}
		
		public function startRending():void
		{
			gameStage.addEventListener(Event.ENTER_FRAME, frameHandler);
		}
		
		public function stopRending():void
		{
			if( gameStage.hasEventListener(Event.ENTER_FRAME) )
				gameStage.removeEventListener(Event.ENTER_FRAME, frameHandler);
		}
		
		public function update():void
		{
			switch(config.mode)
			{
				case Config.MODE_2D:
					main2D.render();
					break;
				case Config.MODE_3D:
					main3D.render();
					break;
			}
		}
		
		protected function frameHandler(event:Event):void
		{
			update();
		}
	}
}